package com.tarry.thread.countdownlatch;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ApplicationStartUp {
    // 所有需要健康检查的服务
    private static List<BaseHealthChecker> checkers;
    // 计数器，需要健康检查的服务个数
    private static CountDownLatch latch = new CountDownLatch(2);

    private final static ApplicationStartUp INSTANCE = new ApplicationStartUp();

    static {
        checkers = Arrays.asList(new CacheHealthChecker(ApplicationStartUp.latch),
                new DatabaseHealthChecker(ApplicationStartUp.latch));
    }

    private ApplicationStartUp() {}

    public static ApplicationStartUp getInstance() {
        return INSTANCE;
    }

    public static boolean checkExternalServices() throws Exception {
        Executor executor = Executors.newFixedThreadPool(checkers.size());
        checkers.forEach(o -> executor.execute(o));
        ApplicationStartUp.latch.await();
        // 查看所有service是否全部启动
        for (final BaseHealthChecker checker : checkers) {
            if (!checker.isServiceUp()) {
                return false;
            }
        }
        return true;
    }

}
